import Page from "@/components/page"
import UiButton from "@/components/ui/UiButton"
import { openModal } from "@/components/ui/UiModal"
import { CommentFields, CommentEntity } from "@/interfaces/CommentEntity"
import { ShopFields } from "@/interfaces/ShopEntity"
import { UserFields } from "@/interfaces/UserEntity"
import { gqlError } from "@/libs/apollo-error"
import { gql, useQuery, useMutation } from "@apollo/client"
import { useMemo, useCallback } from "react"

const GetSelfCommentListQuery = gql`
    query GetCommentList{
        getSelfCommentList{
            ${CommentFields}
            shop{
                ${ShopFields}
            }
            user{
                ${UserFields}
            }
        }
    }
`
const DelCommentMutation = gql`
    mutation DelComment($id:Int!){
        delComment(id:$id)
    }
`
const CommentGoodsPage = () => {
    const { data, refetch } = useQuery(GetSelfCommentListQuery)
    const commentList: CommentEntity[] = useMemo(() => data?.getSelfCommentList || [], [data]);
    const [del] = useMutation(DelCommentMutation, {
        onCompleted: () => refetch(),
        onError(error) {
            gqlError(error)
        },
    })
    const onDel = useCallback((comment: CommentEntity) => {
        openModal(() => ({
            title: "删除后无法恢复，确认要删除吗？",
            onOk() {
                del({ variables: { id: comment.id } })
                return true
            },
        }))
    }, [])
    return (
        <Page>
            <table className="table text-center">
                <thead>
                    <tr>
                        <th>评论编号</th>
                        <th>店铺</th>
                        <th>用户</th>
                        <th>订单编号</th>
                        <th>评分</th>
                        <th>评论</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {commentList.map((item) => (
                        <tr key={item.id}>
                            <td>{item.id}</td>
                            <td>{item.shop.name}</td>
                            <td>{item.user.name}</td>
                            <td>{item.orderId}</td>
                            <td>{item.rate}</td>
                            <td>{item.context}</td>
                            <td>
                                <UiButton
                                    onClick={onDel.bind(null, item)}
                                >
                                    删除
                                </UiButton>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </Page>
    )
}
export default CommentGoodsPage